<?php

namespace app\modules\pay\services;

use app\common\services\BaseService;
use app\config\Constants;
use app\models\PaymentLog;

class PaymentLogService extends BaseService{

    /**
     * 状态
     * @param $order_id
     * @return array
     */
    public static function status($order_id){
        $model = PaymentLog::find()
            ->where(['order_id'=>$order_id])
            ->andWhere(['!=','pay_status',Constants::PAY_STATUS_WAIT])
            ->one();
        return [
            'status'=> $model ? $model->pay_status : Constants::PAY_STATUS_WAIT,
        ];
    }

    /**
     * 获取信息
     * @param $order_no
     * @return PaymentLog|null
     */
    public static function getInfoByPlatformOrderNo($order_no){
        return PaymentLog::findOne(['platform_order_no'=>$order_no]);
    }

    /**
     * 成功状态
     * @param $data
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\Exception
     * @throws \yii\db\StaleObjectException
     */
    public static function successStatus($data){
        $transaction = \Yii::$app->getDb()->beginTransaction();

        $model = PaymentLog::findOne(['platform_order_no'=>$data['out_trade_no']]);
        $model->setAttribute("channel_order_no",$data['wf_trade_no']);
        $model->setAttribute("third_order_no",isset($data['wechat_trade_no']) ? $data['wechat_trade_no'] : $data['alipay_trade_no']);
        $model->setAttribute("pay_status",Constants::PAY_STATUS_SUCCESS);
        $order = $model->goodsOrder;
        $order->setAttribute("status",Constants::ORDER_WAIT);
        $order->setAttribute("pay_status",Constants::PAY_STATUS_SUCCESS);
        if($model->update() === false || $order->update() === false){
            $transaction->rollBack();
            return false;
        }
        $transaction->commit();
        return true;
    }

    /**
     * 退款状态
     * @param $data
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\Exception
     * @throws \yii\db\StaleObjectException
     */
    public static function refundStatus($data){
        $transaction = \Yii::$app->getDb()->beginTransaction();

        $model = PaymentLog::findOne(['platform_order_no'=>$data['out_trade_no']]);
        $model->setAttribute("channel_refund_no",$data['wf_refund_no']);
        $model->setAttribute("third_refund_no",isset($data['wechat_refund_no']) ? $data['wechat_refund_no'] : $data['alipay_refund_no']);
        $model->setAttribute("pay_status",Constants::PAY_STATUS_REFUND);
        $order = $model->goodsOrder;
        $order->setAttribute("pay_status",Constants::PAY_STATUS_REFUND);
        if($model->update() === false || $order->update() === false){
            $transaction->rollBack();
            return false;
        }
        $transaction->commit();
        return true;
    }
}